﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace GeoCoordinateWatcher.WindowsFormsApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            System.Device.Location.GeoCoordinateWatcher watcher = new System.Device.Location.GeoCoordinateWatcher();
            watcher.PositionChanged += Watcher_PositionChanged;
            watcher.Start();
        }

        private void Watcher_PositionChanged(object sender, System.Device.Location.GeoPositionChangedEventArgs<System.Device.Location.GeoCoordinate> e)
        {
            richTextBox1.Text = JsonConvert.SerializeObject(e.Position.Location, Formatting.Indented);
            if (sender is System.Device.Location.GeoCoordinateWatcher watcher)
            {
                watcher.Stop();
                richTextBox1.AppendText($"{Environment.NewLine}AAAA");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            using (System.Device.Location.GeoCoordinateWatcher watcher = new System.Device.Location.GeoCoordinateWatcher())
            {
                var timeSpan = TimeSpan.FromSeconds(1);
                var stopwatch = new Stopwatch();
                watcher.TryStart(false, timeSpan);
                stopwatch.Start();
                while (watcher.Position.Location.IsUnknown)
                {
                    if (stopwatch.Elapsed > timeSpan)
                    {
                        break;
                    }
                    Thread.Sleep(10);
                }
                stopwatch.Stop();
                richTextBox1.Text = JsonConvert.SerializeObject(watcher.Position.Location, Formatting.Indented);
            }
        }
    }
}
